class Post < ActiveRecord::Base

	has_many :posts, :foreign_key => "parent_id", :dependent => :destroy
  has_many :votes
	belongs_to :post
	belongs_to :user
	belongs_to :category
	
	validates_presence_of :title
	validates_presence_of :body
	
	def validate
		errors.add("title", "HTML not allowed in title.") if self.title =~ /(<.+>.+<\/.+>)|(<.+\/>)/m
		errors.add("body", "HTML not allowed in body.") if self.body =~ /(<.*script.*>.+<\/.*script.*>)|(<.+\/>)|(<a.+href.+>)/m
    errors.add("title", "Title too long, must be less then 25 characters.") if self.title.to_s.size > 25
	end

	def find_children
		posts = Post.find_all_by_parent_id(self.id)
		return posts
	end

	def belongs_to_user?(user_id)
		return ( self.user.id == user_id )
	end

  def update_children_category
    children = self.find_children
    children.each do |c|
      c.category_id = self.category_id
      c.save
    end
  end

  def self.sort_posts( posts )
    posts.sort! { |b,a|
      if( a.is_sticky && !b.is_sticky )
        1
      elsif (!a.is_sticky && b.is_sticky)
        -1
      else
        if a.updated_at.nil? && !b.updated_at.nil?
          a.created_at <=> b.updated_at
        elsif !a.updated_at.nil? && b.updated_at.nil?
          a.updated_at <=> b.created_at
        elsif a.updated_at.nil? && b.updated_at.nil?
          a.created_at <=> b.created_at
        else
          a.updated_at <=> b.updated_at
        end
      end
    }

    return posts
  end

  def self.sort_posts_by_date( posts )
    posts.sort! { |b,a|

      if a.updated_at.nil? && !b.updated_at.nil?
        a.created_at <=> b.updated_at
      elsif !a.updated_at.nil? && b.updated_at.nil?
        a.updated_at <=> b.created_at
      elsif a.updated_at.nil? && b.updated_at.nil?
        a.created_at <=> b.created_at
      else
        a.updated_at <=> b.updated_at
      end
    }

    return posts
  end

  def prepare_body
    tags_list = ["b","i","p","em","strong","u"] # ADD MORE TAGS HERE

    tags = String.new
   
    open_tags = Array.new
   
    self.body.each_char { |c|
      tags += c.downcase

      if /(>)/.match(tags)
        tags_list.each do |tag|
          reg1 = Regexp.new("(<\\s*" + tag.to_s + "\\s*>)")
          if reg1.match(tags)
            open_tags += [tag]
            tags = ""
          end
        end
      
        tags_list.each do |tag|
          reg2 = Regexp.new("(<\\s*\\/\\s*" + tag + "\\s*>)")

          if reg2.match(tags) && open_tags.include?(tag)
            open_tags.delete_at(open_tags.index(tag))
            tags = ""
          end
      
        end
        
      end
    }

    if !open_tags.nil?
      open_tags.each do |tag|
        self.body += "</"+tag+">"
      end
      self.save
    end
    self.save
  end

  def self.is_sticky(post_id)
		post = Post.find_by_id(post_id)
		if !post.nil?
			return post.is_sticky
		else
			return false
		end
	end

  def strip_edit_info
    self.body = self.body.gsub( /(<edit_info>.*<\/edit_info>)/m, '')
  end

  def add_edit_info(user_id)
    self.body += "<edit_info>"
    self.body += "\n\n <em> Post edited by " + User.find_by_id(user_id).name.to_s + " at " + (DateTime.now).strftime("%b. %d, %Y -- %I:%M %p") + "</em>"
    self.body += "</edit_info>"
    self.save
  end

  def append_signature(user_id)
    user = User.find_by_id(user_id)
    if !user.nil? && !user.signature.nil?
      self.body += ("\n\n" + user.signature)
      self.save
    end
  end

  def calculate_score
    return Vote.calculate_score( self.id )
  end

  def add_vote( user_id, value )
    Vote.vote( user_id, self.id, value )
  end

    def self.view_level_id( id )
    p = Post.find_by_id( id )
    return (p.category.user_level_rule.view_level_id).to_i
  end

end
